//
//  MyIndentsDetailViewController.m
//  Globalstone
//
//  Created by 刘建峰 on 16/7/19.
//  Copyright © 2016年 yuf. All rights reserved.
//

#import "MyIndentsDetailViewController.h"
#import "SureIndentTableViewCell.h"
#import "PayTypeViewController.h"
static NSString * cellIndentifier = @"SureIndentTableViewCell";


@interface MyIndentsDetailViewController ()<UITableViewDelegate,UITableViewDataSource>
@property (weak, nonatomic) IBOutlet UIView *navView;
@property (weak, nonatomic) IBOutlet UIView *addressView;
@property (weak, nonatomic) IBOutlet UIScrollView *scroView;
@property (weak, nonatomic) IBOutlet UIView *detailView;
@property(nonatomic,strong)NSMutableArray * goodsArray;
@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property(nonatomic,strong)NSDictionary * indentDic;
@property (weak, nonatomic) IBOutlet UILabel *indentStatusLabel;
@property (weak, nonatomic) IBOutlet UILabel *indentNum;
@property (weak, nonatomic) IBOutlet UILabel *dealDate;
@property (weak, nonatomic) IBOutlet UIButton *cancleButton;
@property (weak, nonatomic) IBOutlet UIButton *payButton;

@end

@implementation MyIndentsDetailViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    _goodsArray = [NSMutableArray array];
    _indentDic = [NSDictionary dictionary];
    [self initViewLayout];
    [self getIndentDetail];
    // Do any additional setup after loading the view.
}

- (void)initViewLayout{
    [self adaptiveViewLayout:self.view];
    [self adaptiveViewLayout:self.navView];
    [self adaptiveViewLayout:self.scroView];
    [self adaptiveViewLayout:self.addressView];
    [self adaptiveViewLayout:self.detailView];
    
    _scroView.contentSize = flexibleSize(CGSizeMake(0, 463), NO);
    
    [_tableView registerNib:[UINib nibWithNibName:cellIndentifier bundle:nil] forCellReuseIdentifier:cellIndentifier];
    _tableView.dataSource = self;
    _tableView.delegate = self;
    
    if (_indentStatus>=2 && _indentStatus<=4) {
        _cancleButton.frame = flexibleFrame(CGRectMake(0, 526, 320, 42), NO);
        [_cancleButton setTitle:@"删除订单" forState:UIControlStateNormal];
    }else if (_indentStatus == 5){
        _cancleButton.frame = flexibleFrame(CGRectMake(0, 526, 320, 42), NO);
        [_cancleButton setTitle:@"未支付取消订单" forState:UIControlStateNormal];
    }else if (_indentStatus == 6){
        _cancleButton.frame = flexibleFrame(CGRectMake(0, 526, 320, 42), NO);
        [_cancleButton setTitle:@"支付成功删除订单" forState:UIControlStateNormal];
    }
    
    
}

- (IBAction)back:(id)sender {
    [self backBtn];
}
#pragma mark === 取消订单/删除订单
- (IBAction)cancelIndent:(UIButton *)sender {
    if (![Common getLoginStatus]) {
        [[AppDelegate sharedAppDelegate]ShowLoginPage];
        return;
    }
    NSMutableDictionary  *dic=[NSMutableDictionary dictionary];
    
    [dic setObject:[Common getLoginInfo][@"userId"] forKey:@"museId"];
    [dic setObject:[Common getLoginInfo][Key_User_password] forKey:@"musePwd"];
    [dic setObject:[Common getLoginInfo][Key_User_onlineKey] forKey:@"museOnlineTag"];
    [dic setObject:_indentId forKey:@"mordId"];
    
    
    self.shareApi.delegate=self;
    [self.shareApi  requestOperationWithDic:dic withPath:GS_deleteCancelMallOrder withHttpType:@"POST" withTag:GS_GS_deleteCancelMallOrder];
}
#pragma mark === 立即购买
- (IBAction)buyNow:(id)sender {
    UIStoryboard *secondStroyBoard=[UIStoryboard storyboardWithName:@"SupplyChainStoryboard" bundle:nil];
    PayTypeViewController *page = [secondStroyBoard instantiateViewControllerWithIdentifier:@"PayType"];
    page.payOrderPrice = [NSString stringWithFormat:@"%@",_indentDic[@"mordPrice"]];
    page.payOrderName = @"中磐科技";
    page.payId = [NSString stringWithFormat:@"%@",_indentDic[@"mordNo"]];
    //            page.paySuccessBlock = ^(){
    //                [self backBtn];
    //            };
    [[Common getNavigation]pushViewController:page completion:^{
    }];
}

#pragma mark === 请求订单详情
- (void)getIndentDetail{
    if (![Common getLoginStatus]) {
        [[AppDelegate sharedAppDelegate]ShowLoginPage];
        return;
    }
    NSMutableDictionary  *dic=[NSMutableDictionary dictionary];
    
    [dic setObject:[Common getLoginInfo][@"userId"] forKey:@"museId"];
    [dic setObject:[Common getLoginInfo][Key_User_password] forKey:@"musePwd"];
    [dic setObject:[Common getLoginInfo][Key_User_onlineKey] forKey:@"museOnlineTag"];
    [dic setObject:_indentId forKey:@"mordId"];
    
    self.shareApi.delegate=self;
    [self.shareApi  requestOperationWithDic:dic withPath:GS_queryMyOrderDetail withHttpType:@"POST" withTag:GS_GS_queryMyOrderDetail];
}

#pragma mark  ==== tableViewDelegate

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 28*VerticalRatio();
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 50*VerticalRatio();
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    UIView * view = [[UIView alloc]initWithFrame:flexibleFrame(CGRectMake(0, 0, 320, 28), NO)];
    view.backgroundColor = [UIColor whiteColor];
    
    //公司名称
    UILabel * companyName = [[UILabel alloc]initWithFrame:flexibleFrame(CGRectMake(14, 1, 300, 28), NO)];
    companyName.textColor = [UIColor colorWithWhite:0.447 alpha:1.000];
    companyName.font = [UIFont systemFontOfSize:15*VerticalRatio()];
    companyName.text = [NSString stringWithFormat:@"%@",_indentDic[@"mstoName"]];
    [view addSubview:companyName];
    
    return view;
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    UIView * view = [[UIView alloc]initWithFrame:flexibleFrame(CGRectMake(0, 0, 320, 50), NO)];
    view.backgroundColor = [UIColor whiteColor];
    UILabel * line = [[UILabel alloc]initWithFrame:flexibleFrame(CGRectMake(0, 45, 320, 5), NO)];
    line.backgroundColor = [UIColor colorWithWhite:0.941 alpha:1.000];
    [view addSubview:line];
    
    //运费
    UILabel * transPrice = [[UILabel alloc]initWithFrame:flexibleFrame(CGRectMake(75, 0, 200, 15), NO)];
    transPrice.textColor = [UIColor colorWithWhite:0.447 alpha:1.000];
    transPrice.font = [UIFont systemFontOfSize:12*VerticalRatio()];
   
    transPrice.text = [NSString stringWithFormat:@"运费:￥%.2f",[_indentDic[@"mstoFreight"]floatValue]];;

    [view addSubview:transPrice];
    
    //总计
    UILabel * totalPrice = [[UILabel alloc]initWithFrame:flexibleFrame(CGRectMake(0, 15, 305, 15), NO)];
    totalPrice.textColor = [UIColor colorWithWhite:0.447 alpha:1.000];
    totalPrice.font = [UIFont systemFontOfSize:13*VerticalRatio()];
    totalPrice.textAlignment = NSTextAlignmentRight;
    NSString * price = @"";
    CGFloat pri = 0;
    
    for (NSDictionary * dict in _goodsArray) {
        CGFloat pric = [dict[@"mallGoods"][@"mgooPrice"]floatValue];
        pri += pric;
    }
        
        
    CGFloat trans = [_indentDic[@"mstoFreight"]floatValue];
    price = [NSString stringWithFormat:@"%.2f",pri+trans];
    
    NSMutableAttributedString * str = [[NSMutableAttributedString alloc]initWithString:[NSString stringWithFormat:@"实付款(含运费):￥%@",price]];
    [str addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:15*VerticalRatio()] range:NSMakeRange(9, str.length-9)];
    [str addAttribute:NSForegroundColorAttributeName value:[UIColor colorWithRed:1.000 green:0.467 blue:0.004 alpha:1.000] range:NSMakeRange(9, str.length-9)];
    totalPrice.attributedText = str;
    [view addSubview:totalPrice];
    
    return view;
}

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{

    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return _goodsArray.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 62*VerticalRatio();
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    SureIndentTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:cellIndentifier];
    if (cell == nil) {
        cell = [[SureIndentTableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIndentifier];
    }
        NSDictionary * dic = _goodsArray[indexPath.row];
        cell.goodsName.text = [NSString stringWithFormat:@"%@",dic[@"mallGoods"][@"mgooName"]];
        cell.goodsPrice.text = [NSString stringWithFormat:@"价格:￥%@",dic[@"mallGoods"][@"mgooPrice"]];
        cell.goodsType.text = [NSString stringWithFormat:@"规格:%@/块",dic[@"mallGoods"][@"mgooSpecify"]];
        NSString * image =  [NSString stringWithFormat:@"%@",dic[@"mallGoods"][@"mgooImage"]];
        if (image.length>0) {
            [cell.goodsImage sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@%@",IP_Address_ImageDown_Fresh,image]]];
        }
        
        cell.goodsNum.text = [NSString stringWithFormat:@"x%@",dic[@"modeNum"]];
        
    return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
}


#pragma   mark---- GetADBanner Request Delegate

-(void)fetchDatabaseFinished:(NSMutableDictionary *)database withTag:(NSInteger)tag{
    if (tag==GS_GS_queryMyOrderDetail) {
        if (  [[database valueForKey:@"flag"] integerValue]!=1 ) {
            
            [[CWHUDTips sharedInstance]  showTips:[database valueForKey:@"msg"]  withStatus:1 dismissAfter:1.5];
            
        }else  {
            _indentDic = database[@"result"];
            
            _indentNum.text = [NSString stringWithFormat:@"%@",_indentDic[@"mordNo"]];
            _dealDate.text = [NSString stringWithFormat:@"%@",_indentDic[@"mordCreateTime"]];
            NSString * indentStatus = [NSString stringWithFormat:@"%@",_indentDic[@"mordStatus"]];;
            if ([indentStatus isEqualToString:@"1"]) {
                indentStatus = @"未支付";
            }else if ([indentStatus isEqualToString:@"2"]){
                indentStatus = @"已支付";
            }else if ([indentStatus isEqualToString:@"3"]){
                indentStatus = @"已发货";
            }else if ([indentStatus isEqualToString:@"4"]){
                indentStatus = @"已收货";
            }else if ([indentStatus isEqualToString:@"5"]){
                indentStatus = @"未支付取消订单";
            }else if ([indentStatus isEqualToString:@"6"]){
                indentStatus = @"支付成功删除订单";
            }
            _indentStatusLabel.text = indentStatus;
            
            _goodsArray = database[@"result"][@"mallOrderDetail"];
            [_tableView reloadData];
            
            _tableView.frame = flexibleFrame(CGRectMake(0, 150, 320, 78+_goodsArray.count*62), NO);
            _detailView.frame = flexibleFrame(CGRectMake(0, CGRectGetMaxY(_tableView.frame)/VerticalRatio(), 320, 166), NO);
            if (CGRectGetMaxY(_detailView.frame)>_scroView.contentSize.height) {
                 _scroView.contentSize = flexibleSize(CGSizeMake(0, CGRectGetMaxY(_detailView.frame)/VerticalRatio()), NO);
            }
           
        }
    }else if (tag ==GS_GS_deleteCancelMallOrder){
        if (  [[database valueForKey:@"flag"] integerValue]!=1 ) {
            
            [[CWHUDTips sharedInstance]  showTips:[database valueForKey:@"msg"]  withStatus:1 dismissAfter:1.5];
            
        }else  {
            
            [[CWHUDTips sharedInstance]  showTips:[database valueForKey:@"msg"]  withStatus:1 dismissAfter:1.5];
            [self backBtn];
        }
    }
}

-(void)fetchDatabaseFailed:(NSError *)error message:(NSString *)message{
        
        [self dismissWaitDialog];
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


@end
